/**
 * Created by fudebao on 2017/12/05.
 */
import React from 'react';
import {connect} from 'react-redux';
import {Button, Form, Switch, Input, message, Icon, Select, Radio, Col, Row} from 'antd';
import LanguageInput from 'components/template/language-input/language-input'
const FormItem = Form.Item;
const Option = Select.Option;
import 'styles/pay-setting/payment-method/new-payment-method.scss'
import SSService from 'containers/setting/subject-sheet/subject-sheet.service'
import { messages } from 'share/common'

class NewSubjectSheet extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      params: {},
      loading: false,
      newSheet: {
        i18n: {accountSetDesc: ''},
        accountSetDesc: ''
      },
    };
  }

  componentWillMount() {
    let params = this.props.params;
    if (params && JSON.stringify(params) != "{}") {
        this.setState({
            newSheet:params,
        })
    }
  }

  //校验多语言
  //task 11879
  validateI18n = (accout) => {
      let str = /^[\u4E00-\u9FA5\w\d]*$/u;
      if(!str.test(accout.accountSetDesc) || accout.accountSetDesc.length >100){
        messages('setting.key258'/*不超过100个字符，只能有中文，数字，字母，下划线。*/)
        return false;
      }else{
        return true;
      }
  };

  //新建或编辑
  handleSave = () => {
    const {newSheet} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let account = Object.assign({}, newSheet, values);
        // if (this.validateI18n(account)) {
          if (JSON.stringify(this.props.params) === "{}") {
            this.newAccount(account);
          } else {
            this.editAccount(account);
          }
        // }else {
        //   console.log("er")
        // }
      }
    });
  };

  //新增
  newAccount = (account) => {
    this.setState({loading: true});
    SSService.newAccount(account)
      .then((res) => {
        this.setState({
          newSheet: {
            i18n: {accountSetDesc: '',},
            accountSetDesc: '',
          },
          loading: false,
        });
        this.props.form.resetFields();
        this.props.close(true);
        message.success(messages("common.create.success", {name: messages('setting.key1048'/*科目表*/)}));
      })
  };

  //修改
  editAccount = (account) => {
    this.setState({loading: true});
    SSService.editAccount(account)
      .then((res) => {
        this.setState({
          loading: false,
        });
        this.props.form.resetFields();
        this.props.close(true);
        message.success(messages('setting.key260'/*修改成功*/));
      })

  };

  onCancel = () => {
    this.props.form.resetFields();
    this.setState({
      newSheet: {
        i18n: {accountSetDesc: ''},
        accountSetDesc: ''
      },
    });
    this.props.close();
  };

  handleNewSheetChange = (value, i18n) => {
    let newSheet = this.state.newSheet;
    newSheet.accountSetDesc = value;
    newSheet.i18n = newSheet.i18n ? newSheet.i18n : {};
    newSheet.i18n.accountSetDesc = i18n;
    this.setState({
      newSheet,
    })
  };

  formChange = () => {
    this.setState({
      loading: false,
    });
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const {newSheet} = this.state;
    const formItemLayout = {
      labelCol: {span: 6, offset: 1},
      wrapperCol: {span: 14, offset: 1},
    };
    return (
      <div className="new-payment-method">
        <Form onSubmit={this.handleSave} onChange={this.formChange}>
          <FormItem {...formItemLayout} label={messages('setting.key1049'/*科目表代码*/)}>
            {getFieldDecorator('accountSetCode', {
              rules: [{
                required: true,
                message: messages("common.please.enter")
              },
                {
                  validator: (item, value, callback) => {
                    let str = /^[0-9a-zA-z-_]*$/;
                    if (!str.test(value) || value.length > 35) {
                      callback(messages('setting.key1050'/*不超过35个字符，只能有字母，数字，下划线*/))
                    }
                    callback();
                  }
                }
              ],
              initialValue: this.props.params.accountSetCode || ''
            })(
              <Input disabled={!!this.props.params.id}/>
            )}
          </FormItem>
        </Form>
          <Row style={{marginBottom: 20}}>
            <Col span={6} offset={1} style={{textAlign: 'right'}}>
              <span style={{color: 'red'}}>&nbsp;*</span>{/*科目表名称*/}&nbsp;{messages('setting.key1051'/*科目表名称*/)}：
            </Col>
              <Col span={14} offset={1}>
              <LanguageInput
                isEdit={!!this.props.params.id}
                name={newSheet.accountSetDesc}
                i18nName={newSheet.i18n && newSheet.i18n.accountSetDesc ? newSheet.i18n.accountSetDesc : null}
                nameChange={(value, i18n) => this.handleNewSheetChange(value, i18n)}/>
            </Col>
          </Row>
        <Form>
          <FormItem {...formItemLayout} label={messages('common.column.status')}>
            {getFieldDecorator('enabled', {
              initialValue: this.props.params.id ? this.props.params.enabled : true
            })(
              <Switch checked={this.props.form.getFieldValue('enabled')}
                      checkedChildren={<Icon type="check"/>} unCheckedChildren={<Icon type="cross"/>}/>
            )}
            &nbsp;&nbsp;&nbsp;&nbsp;
            {this.props.form.getFieldValue('enabled') ? messages("common.status.enable") : messages("common.status.disable")}
          </FormItem>
        </Form>
          <div className="slide-footer">
            <Button type="primary"
                    onClick={ this.handleSave}
                    loading={this.state.loading}>{messages("common.save")}</Button>
            <Button onClick={this.onCancel}>{messages("common.cancel")}</Button>
          </div>
      </div>
    )
  }
}


const WrappedNewSubjectSheet = Form.create()(NewSubjectSheet);

function mapStateToProps(state) {
  return {
    company: state.login.company,
  }
}
export default connect(mapStateToProps)(WrappedNewSubjectSheet);
